package com.chalet16.fightflood;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioGroup;
import android.widget.EditText;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class ReportActivity extends Activity implements
		OnCheckedChangeListener, TextWatcher, OnClickListener {
	private GetLocation getloc;

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.report);
		((RadioGroup) findViewById(R.id.radioGroup1))
				.setOnCheckedChangeListener(this);
		((EditText) findViewById(R.id.txtAmount)).addTextChangedListener(this);
		((Button) findViewById(R.id.btnTwitter)).setOnClickListener(this);
		getloc = new GetLocation(getApplicationContext());
	}

	@Override
	protected void onResume() {
		super.onResume();
		getloc.start();
	}

	@Override
	protected void onPause() {
		super.onPause();
		getloc.stop();
	}

	public void onCheckedChanged(RadioGroup group, int checkedId) {
		if (checkedId == R.id.selHave) {
			findViewById(R.id.layoutAmountUnit).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.layoutAmountUnit).setVisibility(View.GONE);
		}
	}

	public void afterTextChanged(Editable s) {
		try {
			if (s.length() != 0) {
				Integer.parseInt(s.toString());
			}
			findViewById(R.id.txtUnit).setVisibility(View.VISIBLE);
		} catch (NumberFormatException nfe) {
			findViewById(R.id.txtUnit).setVisibility(View.GONE);
			((EditText) findViewById(R.id.txtUnit)).setText("");
		}
	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
	}

	public void onClick(View v) {
		String msg = getMessage();
		if (msg != "") {
			twit(msg);
		}
	}

	private String getMessage() {
		String output = getString(R.string.twitter_id) + " ";
		String product = ((EditText) findViewById(R.id.txtProduct)).getText()
				.toString();
		Boolean isHave = ((RadioGroup) findViewById(R.id.radioGroup1))
				.getCheckedRadioButtonId() == R.id.selHave;
		String amount = ((EditText) findViewById(R.id.txtAmount)).getText()
				.toString();
		String unit = ((EditText) findViewById(R.id.txtUnit)).getText()
				.toString();
		String location = ((EditText) findViewById(R.id.txtLocation)).getText()
				.toString();
		Boolean isGPS = ((CheckBox) findViewById(R.id.chkGPS)).isChecked();
		if (product.length() == 0) {
			((EditText) findViewById(R.id.txtProduct))
					.setError(getString(R.string.err_txtProduct));
			return "";
		}
		if (isHave && amount.length() == 0) {
			((EditText) findViewById(R.id.txtAmount))
					.setError(getString(R.string.err_txtAmount));
			return "";
		}
		if (isHave
				&& findViewById(R.id.txtUnit).getVisibility() == View.VISIBLE
				&& unit.length() == 0) {
			((EditText) findViewById(R.id.txtUnit))
					.setError(getString(R.string.err_txtUnit));
			return "";
		}
		if (location.length() == 0) {
			((EditText) findViewById(R.id.txtLocation))
					.setError(getString(R.string.err_txtLocation));
			return "";
		}
		if (isHave) {
			output = output.concat("มี " + product + " : " + amount);
			if (findViewById(R.id.txtUnit).getVisibility() == View.VISIBLE) {
				output = output.concat(" " + unit);
			}
		} else {
			output = output.concat("ไม่มี " + product);
		}
		output = output.concat(" ที่ " + location);
		if (isGPS) {
			if (!getloc.isNetworkEnabled() && !getloc.isGpsEnabled()) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.err_noGPS), Toast.LENGTH_SHORT);
				return "";
			}
			// TODO: Confirm user without GPS
			if (getloc.locate()) {
				Location loc = getloc.getLocation();
				output = output.concat(" //"
						+ Location.convert(loc.getLatitude(),
								Location.FORMAT_DEGREES)
						+ ", "
						+ Location.convert(loc.getLongitude(),
								Location.FORMAT_DEGREES));
			} else {
				Toast.makeText(getApplicationContext(),
						getString(R.string.err_noLocFound), Toast.LENGTH_SHORT);
				return "";
			}
		}
		return output;

	}

	// Code snippet from
	// http://blog.rafaelsanches.com/2010/06/18/using-native-twitter-app-intent-to-share-on-android/
	private void twit(String msg) {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.putExtra(Intent.EXTRA_TEXT, msg);
		intent.setType("text/plain");
		PackageManager pm = getApplicationContext().getPackageManager();
		List<ResolveInfo> activityList = pm.queryIntentActivities(intent, 0);
		int len = activityList.size();
		Boolean foundClient = false;
		for (int i = 0; i < len; i++) {
			ResolveInfo app = (ResolveInfo) activityList.get(i);
			if (getString(R.string.prog_twitterActivity).equals(
					app.activityInfo.name)) {
				ActivityInfo activity = app.activityInfo;
				ComponentName name = new ComponentName(
						activity.applicationInfo.packageName, activity.name);
				intent = new Intent(Intent.ACTION_SEND);
				intent.addCategory(Intent.CATEGORY_LAUNCHER);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				intent.setComponent(name);
				intent.putExtra(Intent.EXTRA_TEXT, msg);
				getApplicationContext().startActivity(intent);
				foundClient = true;
				break;
			}
		}

		// Alternative Method
		if (!foundClient) {
			String query;
			try {
				query = URLEncoder.encode(msg, "utf-8");
				String url = getString(R.string.prog_twitterURL) + query;
				Intent browserIntent = new Intent(Intent.ACTION_VIEW,
						Uri.parse(url));
				startActivity(browserIntent);
			} catch (UnsupportedEncodingException e) {
			}
		}
	}

}
